/**
 * @param {number[]} nums
 * @param {number} lower
 * @param {number} upper
 * @return {number}
 */
 var countFairPairs = function(nums, lower, upper) {
    nums = nums.sort((a,b)=>{
        return a - b;
    });
    const findInd = (num,l,r = nums.length - 1) => {
        while(l < r){
            let mid = Math.floor((l + r) / 2);
            if(nums[mid] < num) l = mid + 1;
            else r = mid;
        }
        return l;
    };
    const findInd1 = (num,l,r = nums.length - 1) => {
        while(l < r){
            let mid = Math.floor((l + r) / 2);
            if(nums[mid] >= num) r = mid;
            else l = mid + 1;
        }
        return l;
    };
    console.log('nums',nums);
    let res = 0;
    for(let i = 0; i < nums.length - 1; i++){
        let lowInd = findInd(nums[i] + lower,i + 1);
        let upInd = findInd1(nums[i] + upper,i + 1);
        if(nums[i] + nums[lowInd] > upper) continue;
        if(nums[i] + nums[lowInd] < lower) continue;
        if(nums[i] + nums[upInd] > upper) upInd--;
        console.log(i,lowInd,upInd);
        res += upInd - lowInd + 1;  
    }
    return res;
};